//
//  ExperienceViewController.m
//  PaiLeXiongProject
//
//  Created by 小獾科技 on 2017/8/15.
//  Copyright © 2017年 小獾科技. All rights reserved.
//

#import "ExperienceViewController.h"
#import "ExperienceListCell.h"
#import "ExperienceAnotherCell.h"
#import "ExperienceApplyModel.h"
#import "ApplyViewController.h"
@interface ExperienceViewController ()<UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITableView *anothertableView;
@property (nonatomic, strong) UISegmentedControl *segment;

@property (nonatomic, strong) NSMutableArray *datasource;//申请数组
@property (nonatomic, strong) NSMutableArray *applyArray;//已报名数组
@property (nonatomic, strong) UIView *alert;
@property (nonatomic, strong) UIView *aview;

@property (nonatomic, copy) NSString *flagStr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) LoadingView *load;

@property (nonatomic, strong) LoadingView *anotherLoad;
@end

@implementation ExperienceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"体验";
    [self configView];//初始化ui
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification) name:@"gotoSee" object:nil];//通知 跳转到已报名界面
    self.view.backgroundColor = ColorWhite;
    _page = 1;
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(ExperienceDoRefresh)];
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(experienceAppend)];
    _anothertableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(ExperienceApplyDoRefresh)];
    _anothertableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(anotherAppend)];
    [_tableView.mj_header beginRefreshing];
    [_anothertableView.mj_header beginRefreshing];
    
    _load = [[LoadingView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT - 64)];
    _load.hidden = YES;
    [_load setReminderLabelTitle:@"糟糕！断网了" andImage:@"noNetweok"];
    [_load.refreshBtn addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventTouchUpInside];
    _load.refreshBtn.hidden = NO;
    [self.view addSubview:_load];
    
    _anotherLoad = [[LoadingView alloc] initWithFrame:CGRectMake(0, 70, GWIDTH, GHEIGHT - 64 - 70)];
    _anotherLoad.hidden = YES;
    [_anotherLoad setReminderLabelTitle:@"暂无报名申请~" andImage:@"anotherLoad"];
    [self.view addSubview:_anotherLoad];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    if([GW_Request sharedInstance].noNetwork)
    {
        _load.hidden = NO;
    }
}

- (void)handleRefresh:(UIButton *)sender
{
    [self ExperienceDoRefresh];
}


- (void)ExperienceDoRefresh
{
    _page = 1;
    [self startGetData];//申请界面的网络请求
}

- (void)experienceAppend//上拉加载
{
    [self startGetData];//申请界面的网络请求
}

//已报名-----------------------------
- (void)ExperienceApplyDoRefresh
{
    _page = 1;
    [self startNetwork];//已报名界面的网络请求
}
- (void)anotherAppend
{
    [self startNetwork];
}

- (void)createAlertView
{
    _alert = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, GHEIGHT)];
    _alert.hidden = YES;
    _alert.backgroundColor = ColorFrom16A(0x000000, 0.8);
    [[[UIApplication sharedApplication].delegate window] addSubview:_alert];
    [_alert bringSubviewToFront:[UIWindow new]];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
    tap.delegate = self;
    [_alert addGestureRecognizer:tap];
    
    _aview = [UIView new];
    _aview.layer.backgroundColor = ColorWhite.CGColor;
    _aview.layer.cornerRadius = 12;
    [_alert addSubview:_aview];
    [_aview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_alert).offset(246);
        make.centerX.equalTo(_alert.mas_centerX);
        make.width.equalTo(@270);
        make.height.equalTo(@181);
    }];
    
    
    //二维码
    NSString *str = [NSString stringWithFormat:@"%@/index/qrcodeOrderEx&order_id=%@", GW_Domain, STRING(_flagStr)];
    str = [NetWork handleUrlStr:str withDict:nil];
    UIImageView *iv = [UIImageView new];
    iv.image = IMAGE(@"");
    [iv sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:nil];
    [_aview addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_aview).offset(40 + 5.6);
        make.centerX.equalTo(_aview.mas_centerX);
        make.width.equalTo(@100);
        make.height.equalTo(@95);
    }];
    
    UILabel *ab = [UILabel new];
    ab.text = @"向商家出示二维码券即可消费";
    ab.textAlignment = 1;
    ab.textColor = ColorFrom16(0x757982);
    ab.font = PFRFONT(10);
    [_aview addSubview:ab];
    [ab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iv.mas_bottom).offset(16.4);
        make.centerX.equalTo(_aview.mas_centerX);
        make.width.greaterThanOrEqualTo(@129);
        make.height.equalTo(@14);
    }];
}
//申请界面的网络请求
- (void)startGetData
{
    _datasource = [NSMutableArray arrayWithCapacity:0];
    @weakobj(self);
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/experience/GetExpGoods", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"体验页申请 %@", resultDict);
        @strongobj(self);
        if(_page == 1)
        {
            [_datasource removeAllObjects];
        }
        NSArray *arr = resultDict[@"data"];
        for (NSDictionary *dict in resultDict[@"data"]) {
            ExperienceApplyModel *model = [GW_Tool getObjFromDictionary:dict byClassName:@"ExperienceApplyModel"];
            [self.datasource addObject:model];
        }
        self.page++;
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        [_tableView reloadData];//申请界面
        
        if (arr.count < kPageSize) {
            [UIView animateWithDuration:0.3 animations:^{
                self.tableView.mj_footer.hidden = YES;// 没有数据说明是最后一页了，隐藏上拉加载
            }];
        } else {
            self.tableView.mj_footer.hidden = NO;
        }
        
        if(self.datasource.count > 0)
        {
            self.load.hidden = YES;
        }
        
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"申请错误%@", error);
        _load.hidden = NO;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

//已报名界面的网络请求
- (void)startNetwork
{
    _applyArray = [NSMutableArray arrayWithCapacity:0];
    
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/experience/GetMyApply", GW_Domain] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"已报名 %@", resultDict);
        if(self.page == 1)
        {
            [_applyArray removeAllObjects];
        }
        NSArray *arr = resultDict[@"data"];
        for (NSDictionary *dict in resultDict[@"data"]) {
            ExperienceApplyModel *model = [GW_Tool getObjFromDictionary:dict byClassName:@"ExperienceApplyModel"];
            [self.applyArray addObject:model];
        }
        self.page++;
        [_anothertableView.mj_header endRefreshing];
        [_anothertableView.mj_footer endRefreshing];
        [_anothertableView reloadData];
        
        if (arr.count < kPageSize) {
            [UIView animateWithDuration:0.3 animations:^{
                self.anothertableView.mj_footer.hidden = YES;// 没有数据说明是最后一页了，隐藏上拉加载
            }];
        } else {
            self.anothertableView.mj_footer.hidden = NO;
        }
        
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"体验 已报名错误 %@", errorMsg);
        [_anothertableView.mj_header endRefreshing];
        [_anothertableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDalegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag == 0000)
        return self.datasource.count;
    else
        return self.applyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == 0000)
    {
        ExperienceApplyModel *model = self.datasource[indexPath.row];
        ExperienceListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        [cell configViewWithModel:model];
        cell.goToApply.tag = 1000 + indexPath.row;
        [cell.goToApply addTarget:self action:@selector(handleGotoApply:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    else
    {//已报名
        ExperienceApplyModel *model = self.applyArray[indexPath.row];
        ExperienceAnotherCell *cell = [tableView dequeueReusableCellWithIdentifier:@"acell"];
        cell.codeBtn.tag = 100 + indexPath.row;
        
        if([[NSString stringWithFormat:@"%@", model.status_val] isEqualToString:@"2"])
        {
            [cell.codeBtn addTarget:self action:@selector(handleCodeBtn:) forControlEvents:UIControlEventTouchUpInside];
        }
        [cell configViewWithModel:model];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(tableView.tag == 0000)
    {
        NSString *lat = [[NSUserDefaults standardUserDefaults] objectForKey:@"lat"];
        NSString *lon = [[NSUserDefaults standardUserDefaults] objectForKey:@"long"];
        ExperienceApplyModel *model = self.datasource[indexPath.row];
       [GW_webView handleWebView:[NSString stringWithFormat:@"%@/product/ExpressDel.html?gid=%@&latitude=%@&longitude=%@", GW_Domain, model.id, lat, lon] viewController:self titleName:@"体验" goodid:nil];
    }
    else
    {//已报名
        NSString *lat = [[NSUserDefaults standardUserDefaults] objectForKey:@"lat"];
        NSString *lon = [[NSUserDefaults standardUserDefaults] objectForKey:@"long"];
        ExperienceApplyModel *model = self.applyArray[indexPath.row];
        [GW_webView handleWebView:[NSString stringWithFormat:@"%@/product/ExpressDel.html?gid=%@&latitude=%@&longitude=%@", GW_Domain, model.eid, lat, lon] viewController:self titleName:@"体验" goodid:nil];
    }
}

//查看二维码
- (void)handleCodeBtn:(UIButton *)sender
{
    ExperienceApplyModel *model = self.applyArray[sender.tag - 100];
    _flagStr = model.id;
    [self refreshCode:model.id];
  
}


// -----无限请求   刷新二维码
- (void)refreshCode:(NSString *)orderSn
{
    [NetWork sendGetRequestURL:[NSString stringWithFormat:@"%@/order/getOrderDet?orderSn=%@&type=%@", GW_Domain, orderSn, @"4"] parameters:nil completionBlockWithSuccess:^(NSDictionary *resultDict) {
        NSLog(@"%@", resultDict);
        if([resultDict[@"data"][@"status"] isEqualToString:@"2"])//如果是2  弹出二维码
        {
            [self createAlertView];//弹出框
            _alert.hidden = NO;
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"订单状态不正确,请刷新重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            
        }
    } andFailure:^(NSError *error, NSString *errorMsg) {
        NSLog(@"%@", errorMsg);
    }];
}


#pragma mark - 立即申请响应方法
- (void)handleGotoApply:(UIButton *)sender
{
    if(!IS_LOGIN)
    {
        MESSAGE_TOAST(@"请先登录");
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotiShowLoginVC object:nil];
        return;
    }
    ExperienceApplyModel *model = self.datasource[sender.tag - 1000];
    ApplyViewController *applyVC = [ApplyViewController new];
    applyVC.strId = model.id;
    applyVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:applyVC animated:YES];
}

//初始化UI
- (void)configView
{
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, 70)];
    _topView.backgroundColor = ColorFrom16(0xffffff);
    [self.view addSubview:_topView];
    
    _segment = [[UISegmentedControl alloc] initWithItems:@[@"申请", @"已报名"]];
    _segment.frame = CGRectMake(GWIDTH / 2 - 62.5, 17.5, 125, 35);
    _segment.selectedSegmentIndex = 0;
    _segment.layer.borderColor = ColorFrom16(0xfede6d).CGColor;
    _segment.layer.borderWidth = 1;
    _segment.layer.cornerRadius = 17.5;
    _segment.layer.masksToBounds = YES;
    [_segment setTitleTextAttributes:[NSDictionary dictionaryWithObject:PFRFONT(14)forKey:NSFontAttributeName] forState:0];
    [_segment addTarget:self action:@selector(handleSegmentAction:) forControlEvents:UIControlEventValueChanged];
    _segment.tintColor = ColorFrom16(0xfede6d);
    [self handleSegmentAction:_segment];
    [_topView addSubview:_segment];
    
    
    //申请
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, GWIDTH, GHEIGHT - 70  - 49 - 64) style:UITableViewStylePlain];
    _tableView.backgroundColor = ColorWhite;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 133;
    _tableView.tableFooterView = [UIView new];
    _tableView.tag = 0000;
    [_tableView registerClass:[ExperienceListCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    
    //已报名
    _anothertableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70, GWIDTH, GHEIGHT - 49 - 64 - 70) style:UITableViewStylePlain];
    _anothertableView.delegate = self;
    _anothertableView.backgroundColor = ColorClear;
    _anothertableView.dataSource = self;
    _anothertableView.hidden = YES;
    _anothertableView.tag = 1111;
    _anothertableView.rowHeight = 110;
    _anothertableView.sectionFooterHeight = 54;
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, GWIDTH, 54)];
    iv.image = IMAGE(@"home_bottom");
    _anothertableView.tableFooterView = iv;
    [_anothertableView registerClass:[ExperienceAnotherCell class] forCellReuseIdentifier:@"acell"];
    [self.view addSubview:_anothertableView];
    
}
#pragma mark - UISegmentControl 响应方法
- (void)handleSegmentAction:(UISegmentedControl *)sender
{
    switch (sender.selectedSegmentIndex) {
        case 0:
            _tableView.hidden = NO;
            _anothertableView.hidden = YES;
            _anotherLoad.hidden = YES;
            break;
        case 1:
        {
            
            if(!IS_LOGIN)
            {
                MESSAGE_TOAST(@"请先登录");
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotiShowLoginVC object:nil];
                return;
            }
//            [_anothertableView.mj_header beginRefreshing];
            if(self.applyArray.count > 0)
            {
                _anotherLoad.hidden = YES;
            }
            else
            {
                _anotherLoad.hidden = NO;
            }
            
            _tableView.hidden = YES;
            _anothertableView.hidden = NO;
        }
            break;
        default:
            break;
    }
}

//通知
- (void)handleNotification
{
    _segment.selectedSegmentIndex = 1;
    [self.anothertableView.mj_header beginRefreshing];
    [self handleSegmentAction:_segment];
}

- (void)viewWillDisappear:(BOOL)animated
{
//    _segment.selectedSegmentIndex = 0;
//    [self handleSegmentAction:_segment];
}


- (void)viewDidDisappear:(BOOL)animated
{
    [self.alert removeAllSubviews];
}
//手势的代理方法
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if([touch.view isDescendantOfView:_aview])
    {
        _alert.hidden = NO;
        return NO;
    }
    else
    {
        _alert.hidden = YES;
        return YES;
    }
}

- (void)handleTap
{
    _alert.hidden = YES;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"gotoSee" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
